package org.example.servlet;

import org.example.service.UserService;
import org.example.service.UserServiceImpl;
import org.example.model.User;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/updateProfile")
public class UpdateProfileServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject result = new JSONObject();
        
        try {
            // 获取用户ID
            HttpSession session = request.getSession();
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                result.put("success", false);
                result.put("message", "请先登录");
                out.print(result.toString());
                return;
            }
            
            // 获取表单数据
            String username = request.getParameter("username");
            String phone = request.getParameter("phone");
            String email = request.getParameter("email");
            
            // 更新用户信息
            User user = new User();
            user.setUserId(userId);
            user.setUsername(username);
            user.setPhone(phone);
            user.setEmail(email);
            
            boolean success = userService.updateProfile(user);
            
            if (success) {
                // 更新session中的用户信息
                session.setAttribute("username", username);
                session.setAttribute("phone", phone);
                session.setAttribute("email", email);
                
                result.put("success", true);
            } else {
                result.put("success", false);
                result.put("message", "更新失败");
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        
        out.print(result.toString());
    }
} 